from django.db import models
from django.core.validators import MinValueValidator
from django.contrib.postgres.fields import ArrayField
from django.conf import settings
import os
from django.utils import timezone


class DataSet(models.Model):
    title = models.CharField(max_length=50, default='')
    file = models.FileField(upload_to='dataset/%Y/%m/%d')
    file_name = models.CharField(max_length=200, default='')
    # test
    author = models.ForeignKey(to='accounts.User', null=True, on_delete=models.SET_NULL)
    # wanjian
    # author = models.CharField(max_length=50, default='wanjian')
    # 这里改成外键更符合逻辑，更加有利于反向查找，数据库一致性，可以避免用户随意填写妨碍搜索。经测试改掉之后直接迁移即可，不会影响其他功能
    # 唯一需要注意的就是原先用到 self.author的地方改成 self.author.real_name即可。其他功能皆无影响。
    # 同理我这里将Datameta里面也修改了，可参考是否采用，谢谢!

    ref_count = models.IntegerField(default=0, validators=(MinValueValidator(0),))
    upload_time = models.DateTimeField(default=timezone.now)
    update_time = models.DateTimeField(default=timezone.now)
    is_public = models.BooleanField(default=True)
    cols = models.IntegerField(validators=(MinValueValidator(0),), default=0)
    rows = models.IntegerField(validators=(MinValueValidator(0),), default=0)
    purpose = models.CharField(max_length=100, default='')
    downloads = models.IntegerField(validators=(MinValueValidator(0),), default=0)
    indexs = ArrayField(models.CharField(max_length=200), default=None, blank=True, null=True)
    views = models.IntegerField(default=0)

    class Meta:
        ordering = ('-upload_time',)

    def get_abs_file_path(self):
        return os.path.join(settings.MEDIA_ROOT, str(self.file))

    def to_dict(self):
        '''
        返回字段dict
        :return:
        '''
        d = {
            'id': self.id,
            'title': self.title,
            'file_name': self.file_name,
            'author': self.author.real_name,
            'ref_count': self.ref_count,
            'upload_time': self.upload_time,
            'update_time': self.update_time,
            'cols': self.cols,
            'rows': self.rows,
            'purpose': self.purpose,
            'downloads': self.downloads
        }
        return d
